<template>
  <div>
    <el-dialog
      :close-on-click-modal="false"
      :model-value="visible"
      title="设备选择"
      width="1200px"
      draggable
      destroy-on-close
      align-center
      @close="closeDialog"
      class="maxhDialog"
    >
      <el-row :gutter="10">
        <!-- 部门树 -->
        <el-col :span="5" class="!p-[0px] h-auto">
          <el-scrollbar style="box-shadow: 0px 0px 12px rgba(3, 8, 72, 0.08)">
            <dept-tree-select-device-eam
              v-model="searchParam.locationId"
              @node-click="handleQuery"
              @finish-loading="treeLoading = $event"
            />
          </el-scrollbar>
        </el-col>

        <!-- 用户列表 -->
        <el-col :span="15">
          <div class="search-container" style="padding: 18px 15px 0">
            <el-form ref="queryFormRef" :model="searchParam" :inline="true">
              <el-form-item label="" class="w-[135px]">
                <el-tree-select
                  placeholder="请选择设备类型"
                  v-model="searchParam.assetTypeId"
                  :data="catalogList"
                  :disabled="assetTypeId != ''"
                  node-key="id"
                  :props="{
                    label: 'assetTypeName',
                    value: 'id',
                    children: 'nodes',
                  }"
                  :render-after-expand="false"
                  :check-strictly="true"
                  clearable
                />
              </el-form-item>
              <el-form-item label="" class="w-[135px]">
                <el-input
                  v-model="searchParam.assetName"
                  placeholder="请输入设备名称"
                  clearable
                  @keyup.enter="search"
                />
              </el-form-item>
              <el-form-item label="" class="w-[135px]">
                <SelectOriganizationDangerGrant
                  @change="(ids:string) => getSelectIds(ids, '使用部门')"
                  @change-data="(datas) => getSelectDatas(datas, '使用部门')"
                  :isCheckStrictly="true"
                  :isMultiple="false"
                  :disabled="false"
                  :data="dataObject('使用部门')"
                  :selectData="searchParam.usingDepartmentId"
                />
              </el-form-item>

              <el-form-item label="" class="w-[135px]">
                <SelectOriganizationDangerGrant
                  @change="(ids:string) => getSelectIds(ids, '维修部门')"
                  @change-data="(datas) => getSelectDatas(datas, '维修部门')"
                  :isCheckStrictly="true"
                  :isMultiple="false"
                  :disabled="false"
                  :data="dataObject('维修部门')"
                  :selectData="searchParam.repairDepartmentId"
                />
              </el-form-item>

              <el-form-item>
                <el-button type="primary" @click="search" class="mini-search"
                  ><i-ep-search
                /></el-button>
                <el-button @click="resetParams" class="mini-search">
                  <i-ep-refresh />
                </el-button>
              </el-form-item>
            </el-form>
          </div>

          <el-card
            shadow="never"
            class="table-container card-table-p15 h-[536px]"
          >
            <el-table
              ref="multipleTable"
              v-loading="loading"
              :data="tableData"
              @select="handleSelectionChange"
              @select-all="handleAllChange"
              @sort-change="onTableSortChanged"
              class="card-table"
              border
              :cell-style="{ 'text-align': 'center' }"
              height="444px"
            >
              <el-table-column
                type="selection"
                width="50"
                align="center"
                fixed="left"
              />
              <el-table-column
                sortable
                label="设备编号"
                prop="assetCode"
                show-overflow-tooltip
                min-width="150"
              />
              <el-table-column
                sortable
                label="设备名称"
                prop="assetName"
                min-width="150"
                show-overflow-tooltip
              />
              <el-table-column
                sortable
                label="品牌型号"
                prop="assetModelNo"
                min-width="150"
                show-overflow-tooltip
              >
                <template #default="scope">
                  <span>{{ scope.row.assetModelNo }}</span>
                  <span v-if="scope.row.assetModelNo">-</span>
                  <span> {{ scope.row.assetBrandName }}</span>
                </template>
              </el-table-column>

              <el-table-column
                sortable
                label="制造商"
                prop="makerName"
                :align="'center'"
                min-width="150"
                show-overflow-tooltip
              />
              <el-table-column
                sortable
                label="出厂编号"
                prop="manufactureCode"
                min-width="150"
                show-overflow-tooltip
              />
              <el-table-column
                sortable
                label="管理部门"
                prop="manageDepartmentName"
                min-width="150"
                show-overflow-tooltip
              >
                <template #default="scope">
                  {{ scope.row.manageDepartmentName }}
                </template>
              </el-table-column>

              <el-table-column
                sortable
                label="使用部门"
                prop="usingDepartmentName"
                min-width="150"
                show-overflow-tooltip
              >
                <template #default="scope">
                  {{ scope.row.usingDepartmentName }}
                </template>
              </el-table-column>

              <el-table-column
                sortable
                label="使用日期"
                prop="usingDate"
                min-width="150"
                show-overflow-tooltip
              >
                <template #default="scope">
                  {{
                    scope.row.usingDate
                      ? dayjs(scope.row.usingDate).format("YYYY-MM-DD")
                      : ""
                  }}
                </template>
              </el-table-column>

              <el-table-column
                sortable
                label="维修部门"
                prop="repairDepartmentName"
                min-width="150"
                show-overflow-tooltip
              >
                <template #default="scope">
                  {{ scope.row.repairDepartmentName }}
                </template>
              </el-table-column>

              <el-table-column
                sortable
                label="设备位置"
                prop="locationId"
                min-width="150"
                show-overflow-tooltip
              >
                <template #default="scope">
                  {{ scope.row.locationName }}
                </template>
              </el-table-column>

              <el-table-column
                sortable
                label="设备状态"
                prop="assetStatus"
                min-width="150"
                show-overflow-tooltip
              >
                <template #default="scope">
                  {{ useDictionary("assetStatus", scope.row.assetStatus) }}
                </template>
              </el-table-column>
            </el-table>

            <el-pagination
              small
              background
              :current-page="pageable.pageNum"
              :page-size="pageable.pageSize"
              :page-sizes="[10, 25, 50, 100]"
              :total="pageable.total"
              layout="total, sizes, prev, pager, next, jumper"
              class="mt-[20px]"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
            />
          </el-card>
        </el-col>

        <!-- 回显树 -->
        <el-col
          :span="4"
          style="box-shadow: 0px 0px 12px rgba(3, 8, 72, 0.08)"
          class="!p-[0px] h-auto"
        >
          <div>
            <el-row class="p-[15px]">
              <el-col :span="18">
                <div class="selectText">
                  已选设备(<span style="color: #0080ff">{{
                    totalMultipleSelection.length
                  }}</span
                  >)
                </div>
              </el-col>
              <el-col :span="6" align="right">
                <el-button size="small" type="danger" @click="delAll" link
                  >清空</el-button
                >
              </el-col>
            </el-row>

            <el-scrollbar height="480px">
              <div>
                <el-row
                  v-for="(item, index) in totalMultipleSelection"
                  :key="index"
                  class="hover-b-blue ml-[8px] mr-[8px] pl-[14px] pr-[14px] name"
                >
                  <el-col :span="20">{{ item.assetName }}</el-col>
                  <el-col :span="4" align="right">
                    <i-ep-CircleCloseFilled
                      class="c-[rgba(0,0,0,.15)]"
                      @click="delSingle(item, index)"
                    />
                  </el-col>
                </el-row>
              </div>
            </el-scrollbar>
          </div>
        </el-col>
      </el-row>

      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="handleSubmit">确 定</el-button>
          <el-button @click="closeDialog">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { useTable, useDictionary } from "@/utils/useTable";
import { ElTable } from "element-plus";
import { filterOrder } from "@/utils/commonHooks";
import dayjs from "dayjs";
import request from "@/utils/request";

defineOptions({
  name: "UpUserOrganization",
  inheritAttrs: false,
});

interface SelectOption {
  id?: string;
}
const emit = defineEmits(["update:visible", "echo-info"]);

const props = defineProps({
  visible: {
    type: Boolean,
    default: () => {
      return false;
    },
  },
  title: {
    type: String,
    default: () => {
      return "";
    },
  },
  id: {
    type: String,
    default: () => {
      return "";
    },
  },
  data: {
    type: Array,
    default: () => {
      return [];
    },
  },
  isMultiple: {
    type: Boolean,
    default: true,
  },
  assetTypeId: {
    type: String,
    default: () => {
      return "";
    },
  },
});

const { visible, isMultiple, assetTypeId } = toRefs(props);

// 组织机构树
const treeLoading = ref(false);
function handleQuery() {
  search();
}
function resetParams() {
  searchParam.value = searchParamInit;
  if (assetTypeId.value) {
    searchParam.value.assetTypeId = assetTypeId.value;
  }
  reset();
}

// 深层拷贝
function deepCopy(val: any) {
  return JSON.parse(JSON.stringify(val));
}

// 表格选择
const totalMultipleSelection: any = ref([]);
// 表格触发全选
function handleAllChange(selecteds: any) {
  if (isMultiple.value) {
    const currentSelection = deepCopy(totalMultipleSelection.value);
    const ids = deepCopy(totalMultipleIds.value);
    if (selecteds.length) {
      tableData.value.map((item: SelectOption) => {
        const indexId = ids.indexOf(item.id);
        if (indexId < 0) {
          totalMultipleSelection.value.push(item);
        }
      });
    } else {
      tableData.value.map((item: SelectOption) => {
        const indexId = ids.indexOf(item.id);
        if (indexId > -1) {
          currentSelection.splice(indexId, 1);
          ids.splice(indexId, 1);
        }
      });
      totalMultipleSelection.value = currentSelection;
    }
  } else {
    delAll();
    ElMessage.warning("单选，请重新选择");
  }
}
// 表格触发单个选择
function handleSelectionChange(val: any, row: SelectOption) {
  let addOptions = false;
  val?.map((item: SelectOption) => {
    if (item.id === row.id) {
      addOptions = true;
    }
  });
  if (!addOptions) {
    const index = totalMultipleIds.value.indexOf(row.id);
    totalMultipleSelection.value.splice(index, 1);
  } else {
    if (isMultiple.value) {
      totalMultipleSelection.value.push(row);
    } else {
      delAll();
      if (multipleTable.value?.toggleRowSelection) {
        multipleTable.value.toggleRowSelection(row, true);
      }
      totalMultipleSelection.value = [row];
    }
  }
}

// 右侧人员选择操作
const multipleTable = ref(ElTable);
// 全部清除
function delAll() {
  totalMultipleSelection.value = [];
  multipleTable.value.clearSelection();
}
// 单个删除
function delSingle(current: SelectOption, index: number) {
  totalMultipleSelection.value.splice(index, 1);
  tableData.value.map((item: SelectOption) => {
    if (item.id === current.id) {
      if (multipleTable.value?.toggleRowSelection) {
        multipleTable.value.toggleRowSelection(item, false);
      }
    }
  });
}

/** 弹窗展开 初始化数据 */
const totalMultipleIds: any = ref([]);
watch(
  () => totalMultipleSelection,
  async (newVal: any) => {
    const ids: any = [];
    newVal.value?.map((item: SelectOption) => ids.push(item.id));
    totalMultipleIds.value = ids;
  },
  { deep: true }
);

// 请求参数
const requestApi = "/eam/equAssetInfo/queryByPage";

// 是否需要分页
const pagination = true;

const initParam = reactive({
  sort: {
    column: "",
    orderBy: "",
  },
});

// 初始化搜索参数数据
const searchParamInit = {
  empNo: "",
  personName: "",
  post: "",
  personStatus: "",
  locationId: "",
  assetTypeId: assetTypeId.value,
};

// 数据请求错误后处理
function requestError() {}

// 数据请求错误后处理
function dataCallBack(data: any) {
  setTimeout(() => {
    data.map((item: SelectOption) => {
      if (totalMultipleIds.value.includes(item.id)) {
        if (multipleTable.value?.toggleRowSelection) {
          multipleTable.value.toggleRowSelection(item, true);
        }
      }
    });
  }, 0);
  return data;
}

// 表格操作 Hooks
const {
  tableData,
  pageable,
  searchParam,
  loading,
  getTableList,
  search,
  reset,
  handleSizeChange,
  handleCurrentChange,
}: any = useTable(
  requestApi,
  initParam,
  searchParamInit,
  pagination,
  dataCallBack,
  requestError
);

onMounted(() => {
  getTableList();
  // 获取下拉树
  getCAtalogList();
  // getBrandList();
});

/** 弹窗展开 初始化数据 */
const oldTotalSelection: any = ref([]);
watch(
  () => props.visible,
  async (newVal: boolean) => {
    if (newVal) {
      searchParam.value.assetTypeId = assetTypeId.value;

      await getTableList();

      totalMultipleSelection.value = deepCopy(props.data);
      oldTotalSelection.value = deepCopy(props.data);
      dataCallBack(tableData.value);
    }
  }
);

/** 关闭表单弹窗 */
function closeDialog() {
  totalMultipleSelection.value = oldTotalSelection.value;
  dataCallBack(tableData.value);
  emit("update:visible", false);
}

/** 确定提交 */
async function handleSubmit() {
  if (!isMultiple.value && totalMultipleSelection.value.length > 1) {
    ElMessage.error("请选择单个人员");
  } else {
    emit("update:visible", false);
    emit("echo-info", totalMultipleSelection.value);
  }
}

// 目录树
const catalogList: any = ref([]);

// 获取内容树数据
const getCAtalogList = async () => {
  // 获取内容树
  await request({
    url: "eam/equAssetType/getAvailableTree",
    method: "POST",
    data: {},
  }).then((res) => {
    catalogList.value = res.data;
  });
};

// 获取资产品牌数据
const brandList: any = ref([]);
const getBrandList = async () => {
  await request({
    url: "eam/eamassetbrand/getList",
    method: "post",
    data: {},
  }).then((res) => {
    brandList.value = res.data;
  });
};

/** 选择组织机构并赋值id  start **/
function getSelectIds(ids: [] | string, item: string) {
  if (item == "维修部门") {
    console.log("维修部门", ids, item);
    // formData.repairManagerId = "";
    // formData.repairManagerName = "";
    // formData.repairDepartmentId = ids;
  }
  if (item == "使用部门") {
    console.log("使用部门", ids, item);
    // formData.usingPersonId = "";
    // formData.usingPersonName = "";
    // formData.usingDepartmentId = ids;
    // personList2.value = [];
    // changeDept(ids, item);
  }
}
/** 选择组织机构并赋值Name   start **/
function getSelectDatas(datas: any, item: any) {
  if (item == "维修部门") {
    searchParam.value.repairDepartmentId = datas.id ? datas.id : "";
  }
  if (item == "使用部门") {
    searchParam.value.usingDepartmentId = datas.id ? datas.id : "";
  }
}

// 组织机构 placeholder值
const dataObject = (item: string) => {
  return {
    name:
      item == "管理部门"
        ? "管理部门"
        : item == "使用部门"
        ? "使用部门"
        : "维修部门",
    defaultProps: {
      children: "nodes",
      label: "organizationName",
      value: "id",
    },
    api: "/system/sysOrganization/getUsableTree",
  };
};

// 组件销毁时调用
onBeforeUnmount(() => {
  emit("update:visible", false);
  closeDialog();
});

// 排序
// 监听表格排序方法
function onTableSortChanged(column: any) {
  const { prop, order } = column;
  console.log(prop, order);

  initParam.sort = {
    column: prop,
    orderBy: filterOrder(order),
  };
}
// 监听页面 initParam 改化，重新获取表格数据
watch(
  () => initParam,
  (newVal) => {
    console.log("排序变化拉", newVal);
    getTableList();
  },
  { deep: true }
);
</script>

<style lang="scss" scoped>
:deep(.maxhDialog .el-dialog__body) {
  // max-height: 660px;
  overflow-y: auto;
  padding: 20px;
  .mini-search {
    padding: 8px 12px;
  }
  .el-card__body {
    padding: 15px;
  }
}
// :deep(.el-dialog__body) {
//   padding-bottom: 0px !important;
//   padding-top: 15px !important;
// }
.name:hover {
  background-color: rgb(236, 245, 255) !important;
  color: var(--el-menu-active-color) !important;
  border-radius: 6px;
  svg {
    color: var(--el-menu-active-color) !important;
  }
}
.name svg {
  cursor: pointer;
}
:deep(.el-form--inline .el-form-item) {
  margin-right: 10px;
  margin-bottom: 18px;
}
:deep(.el-input__wrapper) {
  box-shadow: 0 0 0 1px var(--el-input-border-color, var(--el-border-color))
    inset !important;
}
.el-button svg {
  margin-right: 0;
}
.card-table-p15 {
  :deep(.el-dialog__body) {
    padding: 15px;
  }
  .card-table {
    line-height: normal;
  }
}

:deep(.el-tree) {
  height: 533px;
}
</style>
